<?php

class IViewFilter extends IActionFilter {
	public function after(IController &$controller) {
		$ret = $controller->action()->ret();
		//如果是IView对象
		if (is_object($ret) && isInstanceOf($ret, "IView")) {
			$this->addValues($ret, $controller);
			$ret->display();
		}
		//如果是数组，则视为跳转
		else if (is_array($ret)) {
			if (isset($ret["controller"])) {
				$actionName = isset($ret["action"])?$ret["action"]:IController::defaultAction();
				$params = isset($ret["params"])?$ret["params"]:null;
				if (in_array("forward")) {
					$controller->forward($ret["controller"], $actionName, $params);
				}
				else {
					$controller->redirect($ret["controller"], $actionName, $params);
				}
			}
		}
		//如果为null，则显示默认的视图
		else if (is_null($ret)) {
			$defaultView = IConfig::opt("@view.default");
			if ($defaultView == null) {
				return;
			}
			$opts = IConfig::opt("@view.{$defaultView}");
			if (is_array($opts) && isset($opts["class"])) {
				$class = $opts["class"];
				if (class_exists($class) && is_subclass_of($class, "ITplView")) {
					$view = new $class();
					$this->addValues($view, $controller);
					$view->display();
				}
			}
		}
	}
	
	private function addValues($view, $controller) {
		//加载配置
		$opts = IConfig::opt("@view." . $view->name());
		$view->init($opts);
		
		$view->setController($controller);
		
		$view->put(array(
			"_params" => $controller->context()->request()->params(),
			"_context" => $controller->context(),
			"_consts" => get_defined_constants(),
			"_controller" => $controller,
			"_action" => $controller->action(),
		));
		if ($controller->router() != null) {
			$view->put(array(
				"_base" => $controller->router()->base())
			);
		}
		$view->put(get_object_vars($controller));
	}
}

?>